<template>
  <div class="app-container">
    <!-- 离校基础设置 -->
    <el-table v-loading="loading" :data="gradsettingsList">
      <el-table-column label="毕业年份" align="center" prop="gradYear">
      </el-table-column>
      <el-table-column label="毕业离校人数" align="center" prop="gradNumber">
      </el-table-column>
      <el-table-column label="学生状态" align="center" prop="gradScope">
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.dep_grad_scope"
            :value="scope.row.gradScope"
          />
        </template>
      </el-table-column>
      <el-table-column
        label="毕业离校时间"
        align="center"
        prop="gdpStartTime"
        width="280"
      >
      <template slot-scope="scope">
        {{ scope.row.gdpStartTime == null ? '暂无数据': scope.row.gdpStartTime + '至'  + scope.row.gdpEndTime}}
        </template>
      </el-table-column>

      <el-table-column
        label="饭卡等注销时间"
        align="center"
        prop="cancelStartTime"
        width="280"
      >
      <template slot-scope="scope">
          <span> {{ scope.row.cancelStartTime == null ? '暂无数据': scope.row.cancelStartTime + '至'  + scope.row.cancelEndTime}}</span>
        </template>
      </el-table-column>

      <el-table-column
        label="学生确认时间"
        align="center"
        prop="confirmStartTime"
        width="280"
      >
      <template slot-scope="scope">
        {{ scope.row.confirmStartTime == null ? '暂无数据': scope.row.confirmStartTime + '至'  + scope.row.confirmEndTime}}
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['departure:gradsettings:query']"
            >详情</el-button
          >
          <el-button
            size="mini"
            type="text"
            @click="handleSettings(scope.row)"
            v-hasPermi="['departure:gradsettings:edit']"
            >设置</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 毕业离校设置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="50%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="15%">
        <H3 style="font-weight: bold; margin-left: 5px"
          >{{ form.gradYear }}毕业离校
          <span style="margin-left: 20px">
            离校人数{{ form.gradNumber }}人
          </span>
        </H3>

        <el-form-item label="学生状态" prop="gradScope">
          <el-checkbox-group v-model="form.gradScope" @change="changeGrad">
            <el-checkbox
              v-for="dict in dict.type.dep_grad_scope"
              :key="dict.value"
              :label="dict.value"
              :value="dict.value"
              >{{ dict.label }}</el-checkbox
            >
          </el-checkbox-group>
        </el-form-item>
        <el-form-item label="毕业离校时间" prop="graduation">
          <el-date-picker
            v-model="form.graduation"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd HH:mm:ss"
            style="width: 60%"
            @input="changeTime"
             :picker-options="pickerOptions"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="学生确认时间" prop="pupilDate">
          <el-date-picker
            v-model="form.pupilDate"
            type="datetimerange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            style="width: 60%"
            value-format="yyyy-MM-dd HH:mm:ss"
            @input="changeTime"
             :picker-options="pickerOptions"
          >
          </el-date-picker>
          <div style="color: red;">请给饭卡等结算预留时间。</div>
        </el-form-item>
        <el-form-item label="饭卡等结算时间" prop="cancelStartTime">
          {{ this.form.cancelStartTime }}至{{ this.form.cancelEndTime }}
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listGradsettings,
  getGradsettings,
  delGradsettings,
  addGradsettings,
  updateGradsettings,
  getScopeNumber
} from "@/api/departure/gradsettings";
import dayjs from "dayjs";
export default {
  name: "Gradsettings",
  dicts: ["dep_grad_scope"],
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 毕业离校设置表格数据
      gradsettingsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {
        graduation: [],
        pupilDate: []
      },
       pickerOptions: {
        disabledDate(time) {
          // 禁止选择今天之前的日期
          return time.getTime() < Date.now() - 8.64e7;
        },
      },
      // 表单校验
      rules: {},
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询毕业离校设置列表 */
    getList() {
      this.loading = true;
      listGradsettings(this.queryParams).then((response) => {
        this.gradsettingsList = response.rows;
        // this.gradsettingsList[0].gradScope = ['A','C']
        this.gradsettingsList.forEach((item) => {
          item.gradScope = item.gradScope.split(",");
        });
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
    },
    addOneDay(dateStr) {
      console.log(dateStr)
      const dateParts = dateStr.split("-");
      const date = new Date(
        dateParts[0], // 年份
        dateParts[1] - 1, // 月份是从0开始的，所以要减1
        dateParts[2] // 日
      );

      // 加一天
      date.setDate(date.getDate() + 1);

      // 转换回字符串格式
      const newDateStr = `${date.getFullYear()}-${String(
        date.getMonth() + 1
      ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
      return newDateStr;
    },
    minusOneDay(dateStr) {
      const dateParts = dateStr.split("-");
      const date = new Date(
        dateParts[0], // 年份
        dateParts[1] - 1, // 月份是从0开始的，所以要减1
        dateParts[2] // 日
      );

      // 加一天
      date.setDate(date.getDate() - 1);

      // 转换回字符串格式
      const newDateStr = `${date.getFullYear()}-${String(
        date.getMonth() + 1
      ).padStart(2, "0")}-${String(date.getDate()).padStart(2, "0")}`;
      return newDateStr;
    },
   // 安全地格式化后端时间
    formatDate(dateString) {
      return dayjs(dateString).format("YYYY-MM-DD HH:mm:ss");
    },
    changeTime() {
      this.form.cancelStartTime = ''
      this.form.cancelEndTime = ''
      if(this.form.graduation && this.form.pupilDate){
        console.log(this.form.graduation, this.form.pupilDate,'fdsjfghjsdkgjksd');
      this.form.cancelStartTime = this.form.graduation[1]
      this.form.cancelEndTime =  this.form.pupilDate[0]
      }
      this.$nextTick(() => {
        this.$forceUpdate();
      });
    },
    changeGrad(data) {
      console.log(data,'data')
      let gradNumber = data.join(',')
      getScopeNumber(gradNumber).then(res => {
        
        this.form.gradNumber = res.data
        console.log(res,this.form.gradNumber,'renshu ')
      })
    },
    /** 设置弹窗操作 */
    handleSettings(row) {
    
      const dgsId = row.dgsId;
      getGradsettings(dgsId).then((response) => {
        console.log(response, this.form, "response");
        this.form = response.data;
        if((response.data.gdpStartTime &&response.data.gdpEndTime) || (response.data.confirmStartTime && response.data.confirmEndTime) ) {
      
       this.form.graduation = [
            this.formatDate(response.data.gdpStartTime),
            this.formatDate(response.data.gdpEndTime),
          ];
       
       this.form.pupilDate = [
            this.formatDate(response.data.confirmStartTime),
            this.formatDate(response.data.confirmEndTime),
          ];
       
        // let pupilDateList =[]
        // pupilDateList[0] =response.data.confirmStartTime
        // pupilDateList[1] =response.data.confirmEndTime
        // // this.form.pupilDate = pupilDateList
        // this.$set(this.form,'pupilDate',pupilDateList)

        }
     
        this.form.gradScope = this.form.gradScopes
        
        
        
       
        this.open = true;
      this.title = "离校设置";
      
      });
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$router.push({ path: '/departure/gradsettings/departureDetails',query: {dgsId:row.dgsId} })
      
      // getGradsettings(dgsId).then((response) => {
      //   this.form = response.data;
      //   this.open = true;
      //   this.title = "修改毕业离校设置";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.gdpStartTime = this.form.graduation[0]
      this.form.gdpEndTime = this.form.graduation[1]
      this.form.confirmStartTime = this.form.pupilDate[0]
      this.form.confirmEndTime = this.form.pupilDate[1]
      this.form.gradScope = this.form.gradScopes.join(',')
      this.$refs["form"].validate(valid => {
        if (valid) {
            updateGradsettings(this.form).then(response => {
              this.$modal.msgSuccess("设置成功");
              this.open = false;
              this.getList();
            });
        }
      });
    },
  },
};
</script>
